// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: GPL-3.0-or-later

package xyz.apiote.bimba.czwek.settings.feeds

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.edit
import com.github.jershell.kbson.KBson
import kotlinx.serialization.Serializable
import xyz.apiote.bimba.czwek.api.Server
import java.net.URLEncoder

@Serializable
@OptIn(ExperimentalStdlibApi::class)
data class FeedsSettings(val settings: MutableMap<String, FeedSettings>) {
	fun activeFeeds() = settings.count { it.value.enabled && it.value.useOnline }
	fun getIDs() = settings.filter { it.value.enabled && it.value.useOnline }.keys.joinToString(",")

	fun save(context: Context, server: Server) {
		val doc = KBson().dump(serializer(), this).toHexString()
		val feedsPreferences =
			context.getSharedPreferences("feeds_settings", AppCompatActivity.MODE_PRIVATE)
		feedsPreferences.edit {
			val key = URLEncoder.encode(server.apiPath, "utf-8")
			putString(key, doc)
		}
	}

	companion object {
		fun load(context: Context, apiPath: String = Server.get(context).apiPath): FeedsSettings {
			val doc = context.getSharedPreferences(
				"feeds_settings",
				Context.MODE_PRIVATE
			).getString(URLEncoder.encode(apiPath, "utf-8"), null)
			return doc?.let { KBson().load(serializer(), doc.hexToByteArray()) } ?: FeedsSettings(
				mutableMapOf()
			)
		}
	}
}

@Serializable
data class FeedSettings(
	val enabled: Boolean,
	val useOnline: Boolean
)

fun migrateFeedsSettings(context: Context, server: Server = Server.get(context)) {
	val shp =
		context.getSharedPreferences(
			URLEncoder.encode(server.apiPath, "utf-8"),
			AppCompatActivity.MODE_PRIVATE
		)
	if (shp.all.isEmpty()) {
		return
	}

	val feedsSettings = FeedsSettings(mutableMapOf())
	shp.all.forEach { (feedID, enabled) ->
		if (enabled as Boolean) {
			feedsSettings.settings[feedID] = FeedSettings(enabled = true, useOnline = true)
		}
	}
	shp.edit {
		clear()
	}
	feedsSettings.save(context, server)
}
